// LostFoundCommentServiceImpl.java
package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.dto.CommentDTO;
import com.csxy.six.entity.LostFoundComment;
import com.csxy.six.mapper.LostFoundCommentMapper;
import com.csxy.six.service.LostFoundCommentService;
import com.csxy.six.util.BeanConverter;
import com.csxy.six.util.SecurityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class LostFoundCommentServiceImpl extends ServiceImpl<LostFoundCommentMapper, LostFoundComment>
        implements LostFoundCommentService {

    @Override
    public List<CommentDTO> getCommentsByItem(Long itemId, Integer itemType) {
        List<LostFoundComment> comments;
        if (itemType == 1) {
            comments = lambdaQuery().eq(LostFoundComment::getLostId, itemId).list();
        } else {
            comments = lambdaQuery().eq(LostFoundComment::getFoundId, itemId).list();
        }

        return comments.stream()
                .map(BeanConverter::toCommentDTO)
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Long addComment(CommentDTO commentDTO, Long userId) {
        if (!SecurityUtil.isOwnerOrAdmin(userId)) {
            throw new RuntimeException("无权评论");
        }

        LostFoundComment comment = new LostFoundComment();
        comment.setUserId(userId);
        comment.setContent(commentDTO.getContent());

        if (commentDTO.getItemType() == 1) {
            comment.setLostId(commentDTO.getItemId());
        } else {
            comment.setFoundId(commentDTO.getItemId());
        }

        save(comment);
        return comment.getCommentId();
    }

    @Override
    @Transactional
    public boolean deleteComment(Long commentId, Long userId) {
        LostFoundComment comment = getById(commentId);
        if (comment == null || (!comment.getUserId().equals(userId) && !SecurityUtil.isAdmin())) {
            return false;
        }
        return removeById(commentId);
    }
}